package com.app.utils;

import com.app.domain.hsy.ResponseResult;
import com.app.domain.jgaeb.LoginCookie;
import com.app.domain.jwjb.SaveDataResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.cert.X509Certificate;
import java.util.*;

public class HttpClients {
    private static PoolingHttpClientConnectionManager connMgr;
    private static RequestConfig requestConfig;
    private static final int MAX_TIMEOUT = 30000;

    public static String doPost(final String apiUrl, final Map<String, Object> params) throws Exception {
        final CloseableHttpClient httpClient = org.apache.http.impl.client.HttpClients.createDefault();
        String httpStr = null;
        CloseableHttpResponse response = null;
        try {
            final HttpPost httpPost = new HttpPost(apiUrl);
            httpPost.setConfig(HttpClients.requestConfig);
            final List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size());
            for (final Map.Entry<String, Object> entry : params.entrySet()) {
                final NameValuePair pair = (NameValuePair) new BasicNameValuePair((String) entry.getKey(), entry.getValue().toString());
                pairList.add(pair);
            }
            httpPost.setEntity((HttpEntity) new UrlEncodedFormEntity((Iterable) pairList, Charset.forName("UTF-8")));
            response = httpClient.execute((HttpUriRequest) httpPost);
            System.out.println(response.toString());
            final HttpEntity entity = response.getEntity();
            httpStr = EntityUtils.toString(entity, "UTF-8");
            System.out.println(httpStr);
        } catch (IOException e) {
            e.printStackTrace();
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException f) {
                    f.printStackTrace();
                }
            }
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e2) {
                    e2.printStackTrace();
                }
            }
        }
        return httpStr;
    }

    public static Map<String, Object> doPost1(final String apiUrl, final Map<String, Object> params) throws Exception {
//         CloseableHttpClient httpClient = org.apache.http.impl.client.HttpClients.createDefault();
        Map<String, Object> result = new HashMap<>();
        CookieStore cookieStore = new BasicCookieStore();
        CloseableHttpClient httpClient = org.apache.http.impl.client.HttpClients.custom()
                .setDefaultCookieStore(cookieStore)
                .build();

        String httpStr = null;
        CloseableHttpResponse response = null;
        try {
            final HttpPost httpPost = new HttpPost(apiUrl);
            httpPost.setConfig(HttpClients.requestConfig);
            final List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size());
            for (final Map.Entry<String, Object> entry : params.entrySet()) {
                final NameValuePair pair = (NameValuePair) new BasicNameValuePair((String) entry.getKey(), entry.getValue().toString());
                pairList.add(pair);
            }
            httpPost.setEntity((HttpEntity) new UrlEncodedFormEntity((Iterable) pairList, Charset.forName("UTF-8")));
            response = httpClient.execute((HttpUriRequest) httpPost);
            List<Cookie> cookieList = cookieStore.getCookies();
            /*for (int i = 0; i < cookieList.size(); i++) {
                System.out.println("Local cookie: " + cookieList.get(i).get);
            }*/
            List<LoginCookie> loginCookieList = new ArrayList<>();
            for (Cookie cookie : cookieList) {
                LoginCookie loginCookie = new LoginCookie();
                loginCookie.setName(cookie.getName());
                loginCookie.setValue(cookie.getValue());
                loginCookie.setDomain(cookie.getDomain());
                loginCookie.setPath(cookie.getPath());
                loginCookieList.add(loginCookie);
            }
            result.put("cookie", loginCookieList);
            System.out.println(response.toString());
            final HttpEntity entity = response.getEntity();
            httpStr = EntityUtils.toString(entity, "UTF-8");
            result.put("httpStr", httpStr);
            System.out.println(httpStr);
        } catch (IOException e) {
            e.printStackTrace();
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException f) {
                    f.printStackTrace();
                }
            }
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e2) {
                    e2.printStackTrace();
                }
            }
        }
        return result;
    }

    public static String doPost(final String apiUrl, final String json) {
        final CloseableHttpClient httpClient = org.apache.http.impl.client.HttpClients.createDefault();
        String httpStr = null;
        final HttpPost httpPost = new HttpPost(apiUrl);
        CloseableHttpResponse response = null;
        final ResponseResult result = new ResponseResult();
        try {
            final StringEntity stringEntity = new StringEntity(json, "UTF-8");
            stringEntity.setContentEncoding("UTF-8");
            stringEntity.setContentType("application/json");
            httpPost.setConfig(HttpClients.requestConfig);
            httpPost.addHeader("Content-type", "application/json; charset=utf-8");
            httpPost.setHeader("Accept", "application/json");
            httpPost.setEntity((HttpEntity) stringEntity);
            response = httpClient.execute((HttpUriRequest) httpPost);
            final HttpEntity entity = response.getEntity();
            httpStr = EntityUtils.toString(entity, "UTF-8");
            System.out.println("接口返回结果信息：" + httpStr);
        } catch (IOException e) {
            e.printStackTrace();
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException f) {
                    f.printStackTrace();
                }
            }
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e2) {
                    e2.printStackTrace();
                }
            }
        }
        return httpStr;
    }

    public static String doGet(final String url) {
        return doGet(url, new HashMap<String, Object>());
    }

    public static String doGet(final String url, final Map<String, Object> params) {
        final StringBuffer param = new StringBuffer();
        String httpStr = null;
        int i = 0;
        for (final String key : params.keySet()) {
            if (i == 0) {
                param.append("?");
            } else {
                param.append("&");
            }
            param.append(key).append("=").append(params.get(key));
            ++i;
        }
        final String apiUrl = url + (Object) param;
        final HttpClient httpclient = (HttpClient) org.apache.http.impl.client.HttpClients.createDefault();
        try {
            final HttpGet httpPost = new HttpGet(apiUrl);
            final HttpResponse response = httpclient.execute((HttpUriRequest) httpPost);
            final int statusCode = response.getStatusLine().getStatusCode();
            final HttpEntity entity = response.getEntity();
            if (entity != null) {
                entity.getContent();
                httpStr = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return httpStr;
    }

    /* public static String doPost(final String apiUrl, Map<String, String> map) throws Exception {
         return  doPost(apiUrl, new HashMap<String, Object>());
     }*/
    public static String requestPost1(final String url, String requestJson, List<LoginCookie> cookies) {

//       final CloseableHttpClient httpClient = org.apache.http.impl.client.HttpClients.createDefault();
        CookieStore cookieStore = new BasicCookieStore();
        //添加cookie
        for (LoginCookie cookie : cookies) {
            System.out.println(cookie);
            BasicClientCookie cookie1 = new BasicClientCookie(cookie.getName(), cookie.getValue());
            //放入cookiestore
            cookie1.setDomain(cookie.getDomain());
            cookie1.setPath(cookie.getPath());
            cookieStore.addCookie(cookie1);

        }
        ;
        CloseableHttpClient httpClient = org.apache.http.impl.client.HttpClients.custom()
                .setDefaultCookieStore(cookieStore)//设置Cookie
                .build();
        final HttpPost httpPost = new HttpPost(url);
        HttpEntity entity = null;
        String httpStr = "";
        final ResponseResult result = new ResponseResult();
        try {
            httpPost.addHeader("Content-type", "application/json; charset=utf-8");
            entity = new StringEntity(requestJson, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            CloseableHttpResponse httpResponse = null;
            httpResponse = httpClient.execute(httpPost);
            final HttpEntity responseEntity = httpResponse.getEntity();
            httpStr = EntityUtils.toString(responseEntity, "UTF-8");
        } catch (IOException e) {
            System.out.println("HttpClient requestPost Execute Error:" + e);
            httpPost.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException f) {
                System.out.println("HttpClient requestPost Close httpClient Error:" + f);
            }
        } finally {
            httpPost.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException e2) {
                System.out.println("HttpClient requestPost Close httpClient Error:" + e2);
            }
        }
        return httpStr;
    }

    public static String requestPost(final String url, String requestJson) {

        final CloseableHttpClient httpClient = org.apache.http.impl.client.HttpClients.createDefault();
        final HttpPost httpPost = new HttpPost(url);
        HttpEntity entity = null;
        String httpStr = "";
        final ResponseResult result = new ResponseResult();
        try {
            httpPost.addHeader("Content-type", "application/json; charset=utf-8");
            entity = new StringEntity(requestJson, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            CloseableHttpResponse httpResponse = null;
            httpResponse = httpClient.execute(httpPost);
            final HttpEntity responseEntity = httpResponse.getEntity();
            httpStr = EntityUtils.toString(responseEntity, "UTF-8");
        } catch (IOException e) {
            System.out.println("HttpClient requestPost Execute Error:" + e);
            httpPost.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException f) {
                System.out.println("HttpClient requestPost Close httpClient Error:" + f);
            }
        } finally {
            httpPost.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException e2) {
                System.out.println("HttpClient requestPost Close httpClient Error:" + e2);
            }
        }
        return httpStr;
    }

    public static String requestPost(final String url, String requestJson, Map map, String source, String token) {

        final CloseableHttpClient httpClient = org.apache.http.impl.client.HttpClients.createDefault();
        final HttpPost httpPost = new HttpPost(url);
        HttpEntity entity = null;
        String httpStr = "";
        final ResponseResult result = new ResponseResult();
        try {
            entity = new StringEntity(requestJson, ContentType.APPLICATION_JSON);
            if (StringUtils.isNotEmpty(source)) {
                httpPost.setHeader("source", source);
            }
            httpPost.setHeader("token", token);
            httpPost.setEntity(entity);
            CloseableHttpResponse httpResponse = null;
            httpResponse = httpClient.execute(httpPost);
            final HttpEntity responseEntity = httpResponse.getEntity();
            httpStr = EntityUtils.toString(responseEntity, "UTF-8");
        } catch (IOException e) {
            System.out.println("HttpClient requestPost Execute Error:" + e);
            httpPost.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException f) {
                System.out.println("HttpClient requestPost Close httpClient Error:" + f);
            }
        } finally {
            httpPost.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException e2) {
                System.out.println("HttpClient requestPost Close httpClient Error:" + e2);
            }
        }
        return httpStr;
    }

    public static String msclRequestPost(final String url, String requestJson, String token) {

        final CloseableHttpClient httpClient = org.apache.http.impl.client.HttpClients.createDefault();
        final HttpPost httpPost = new HttpPost(url);
        HttpEntity entity = null;
        String httpStr = "";
        final ResponseResult result = new ResponseResult();
        try {
            entity = new StringEntity(requestJson, ContentType.APPLICATION_JSON);
            httpPost.setHeader("Paas-Auth", "bearer " + token);
//            httpPost.setHeader("Tenant-Id",tenant_id);
            httpPost.setEntity(entity);
            CloseableHttpResponse httpResponse = null;
            httpResponse = httpClient.execute(httpPost);
            final HttpEntity responseEntity = httpResponse.getEntity();
            httpStr = EntityUtils.toString(responseEntity, "UTF-8");
        } catch (IOException e) {
            System.out.println("HttpClient requestPost Execute Error:" + e);
            httpPost.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException f) {
                System.out.println("HttpClient requestPost Close httpClient Error:" + f);
            }
        } finally {
            httpPost.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException e2) {
                System.out.println("HttpClient requestPost Close httpClient Error:" + e2);
            }
        }
        return httpStr;
    }

    public static Map<String, Object> cxlqRequestPost(final String url, String requestJson, String token) {
        Map<String, Object> map = new HashMap<>();
        final CloseableHttpClient httpClient = org.apache.http.impl.client.HttpClients.createDefault();
        final HttpPost httpPost = new HttpPost(url);
        HttpEntity entity = null;
        String httpStr = "";
        final ResponseResult result = new ResponseResult();
        int statusCode = 0;
        try {
            entity = new StringEntity(requestJson, ContentType.APPLICATION_JSON);
            httpPost.setHeader("X-Authorization", token);
//            httpPost.setHeader("Tenant-Id",tenant_id);
            httpPost.setEntity(entity);
            CloseableHttpResponse httpResponse = null;
            httpResponse = httpClient.execute(httpPost);
            statusCode = httpResponse.getStatusLine().getStatusCode();
            final HttpEntity responseEntity = httpResponse.getEntity();
            httpStr = EntityUtils.toString(responseEntity, "UTF-8");
        } catch (IOException e) {
            System.out.println("HttpClient requestPost Execute Error:" + e);
            httpPost.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException f) {
                System.out.println("HttpClient requestPost Close httpClient Error:" + f);
            }
        } finally {
            httpPost.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException e2) {
                System.out.println("HttpClient requestPost Close httpClient Error:" + e2);
            }
        }
        map.put("httpStr", httpStr);
        map.put("statusCode", statusCode);
        return map;
    }

    public static String cxlcRequestPost(final String url, String requestJson, String token) {
        final CloseableHttpClient httpClient = org.apache.http.impl.client.HttpClients.createDefault();
        final HttpPost httpPost = new HttpPost(url);
        HttpEntity entity = null;
        String httpStr = "";
        try {
            entity = new StringEntity(requestJson, ContentType.APPLICATION_JSON);
            httpPost.setHeader("FaApiToken", token);
//            httpPost.setHeader("Tenant-Id",tenant_id);
            httpPost.setEntity(entity);
            CloseableHttpResponse httpResponse = null;
            httpResponse = httpClient.execute(httpPost);
            final HttpEntity responseEntity = httpResponse.getEntity();
            httpStr = EntityUtils.toString(responseEntity, "UTF-8");
        } catch (IOException e) {
            System.out.println("HttpClient requestPost Execute Error:" + e);
            httpPost.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException f) {
                System.out.println("HttpClient requestPost Close httpClient Error:" + f);
            }
        } finally {
            httpPost.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException e2) {
                System.out.println("HttpClient requestPost Close httpClient Error:" + e2);
            }
        }
        return httpStr;
    }

    public static String ezmebRequestPost(final String url, String requestJson, String token) {

        final CloseableHttpClient httpClient = org.apache.http.impl.client.HttpClients.createDefault();
        final HttpPost httpPost = new HttpPost(url);
        HttpEntity entity = null;
        String httpStr = "";
        final ResponseResult result = new ResponseResult();
        try {
            entity = new StringEntity(requestJson, ContentType.APPLICATION_JSON);
            httpPost.setHeader("token", token);
//            httpPost.setHeader("Tenant-Id",tenant_id);
            httpPost.setEntity(entity);
            CloseableHttpResponse httpResponse = null;
            httpResponse = httpClient.execute(httpPost);
            final HttpEntity responseEntity = httpResponse.getEntity();
            httpStr = EntityUtils.toString(responseEntity, "UTF-8");
        } catch (IOException e) {
            System.out.println("HttpClient requestPost Execute Error:" + e);
            httpPost.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException f) {
                System.out.println("HttpClient requestPost Close httpClient Error:" + f);
            }
        } finally {
            httpPost.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException e2) {
                System.out.println("HttpClient requestPost Close httpClient Error:" + e2);
            }
        }
        return httpStr;
    }


    public static String requestPost(final String url, String authorization, String tenant_id) {

        final CloseableHttpClient httpClient = org.apache.http.impl.client.HttpClients.createDefault();
        final HttpPost httpPost = new HttpPost(url);
        HttpEntity entity = null;
        String httpStr = "";
        final ResponseResult result = new ResponseResult();
        try {
//            entity = new StringEntity(requestJson, ContentType.APPLICATION_JSON);
            httpPost.setHeader("Authorization", authorization);
            httpPost.setHeader("Tenant-Id", tenant_id);
            httpPost.setEntity(entity);
            CloseableHttpResponse httpResponse = null;
            httpResponse = httpClient.execute(httpPost);
            final HttpEntity responseEntity = httpResponse.getEntity();
            httpStr = EntityUtils.toString(responseEntity, "UTF-8");
        } catch (IOException e) {
            System.out.println("HttpClient requestPost Execute Error:" + e);
            httpPost.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException f) {
                System.out.println("HttpClient requestPost Close httpClient Error:" + f);
            }
        } finally {
            httpPost.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException e2) {
                System.out.println("HttpClient requestPost Close httpClient Error:" + e2);
            }
        }
        return httpStr;
    }

    public static String requestPost(final String url, String requestJson, Map<String, String> map) {
        final CloseableHttpClient httpClient = org.apache.http.impl.client.HttpClients.createDefault();
        final HttpPost httpPost = new HttpPost(url);
        HttpEntity entity = null;
        String httpStr = "";
        final ResponseResult result = new ResponseResult();
        try {
            entity = new StringEntity(requestJson, ContentType.APPLICATION_JSON);
            Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> next = iterator.next();
                httpPost.setHeader(next.getKey(), next.getValue());
            }

            httpPost.setEntity(entity);
            CloseableHttpResponse httpResponse = null;
            httpResponse = httpClient.execute(httpPost);
            final HttpEntity responseEntity = httpResponse.getEntity();
            httpStr = EntityUtils.toString(responseEntity, "UTF-8");
        } catch (IOException e) {
            System.out.println("HttpClient requestPost Execute Error:" + e);
            httpPost.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException f) {
                System.out.println("HttpClient requestPost Close httpClient Error:" + f);
            }
        } finally {
            httpPost.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException e2) {
                System.out.println("HttpClient requestPost Close httpClient Error:" + e2);
            }
        }
        return httpStr;
    }

    /**
     * 发送POST请求
     *
     * @param url     请求的URL
     * @param json    JSON格式的数据
     * @param headers 包含HTTP头信息的Map
     * @return 响应结果
     */
    public static String sendPost(String url, String json, Map<String, String> headers) throws IOException {
        if (url == null || url.isEmpty()) {
            throw new IllegalArgumentException("URL不能为空");
        }
        if (json == null) {
            throw new IllegalArgumentException("JSON数据不能为空");
        }

        URL obj = new URL(url);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

        // 设置自定义 SSLContext（替代 disableSslVerification）
        try {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[]{new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                }

                public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                }
            }}, new java.security.SecureRandom());
            con.setSSLSocketFactory(sslContext.getSocketFactory());
            con.setHostnameVerifier((hostname, session) -> true);
        } catch (Exception e) {
            throw new RuntimeException("SSL配置失败", e);
        }

        // 设置请求方法为POST
        con.setRequestMethod("POST");

        // 设置默认请求头
        con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        con.setRequestProperty("Accept", "application/json");

        // 添加自定义请求头
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                con.setRequestProperty(entry.getKey(), entry.getValue());
            }
        }

        // 设置超时时间
        con.setConnectTimeout(10000);
        con.setReadTimeout(30000);

        // 启用输出流以发送数据
        con.setDoOutput(true);

        // 写入JSON数据到输出流
        try (OutputStream os = con.getOutputStream()) {
            byte[] input = json.getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }

        // 获取响应码
        int responseCode = con.getResponseCode();
        // 可替换为日志框架输出
        System.out.println("Response Code: " + responseCode);

        // 根据响应码选择正确的输入流
        InputStream inputStream;
        if (responseCode >= 400) {
            inputStream = con.getErrorStream();
        } else {
            inputStream = con.getInputStream();
        }

        // 读取响应内容
        StringBuilder response;
        try (java.util.Scanner s = new java.util.Scanner(con.getInputStream()).useDelimiter("\\A")) {
            response = s.hasNext() ? new StringBuilder(s.next()) : new StringBuilder();
        } catch (IOException e) {
            e.printStackTrace();
            throw new IOException(e);
        } finally {
            con.disconnect(); // 显式断开连接
        }
        return response.toString();
    }


    /**
     * 禁用SSL验证
     * 此方法通过创建一个信任所有证书的信任管理器来配置SSLContext，
     * 从而使SSL连接不进行证书验证，常用于开发环境或特殊测试场景
     * 注意：在生产环境中使用此方法会带来安全风险，因为它允许信任所有SSL证书
     */
    public static void disableSslVerification() {
        try {
            // 创建一个信任所有证书的信任管理器
            TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        public X509Certificate[] getAcceptedIssuers() {
                            return null;
                        }

                        public void checkClientTrusted(X509Certificate[] certs, String authType) {
                        }

                        public void checkServerTrusted(X509Certificate[] certs, String authType) {
                        }
                    }
            };

            // 初始化SSLContext
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static String requestPost1(final String url, String requestJson, Map<String, String> param) {
        final CloseableHttpClient httpClient = org.apache.http.impl.client.HttpClients.createDefault();
        final HttpPost httpPost = new HttpPost(url);
        HttpEntity entity = null;
        HttpEntity multipart = null;
        String httpStr = "";
        ContentType contentType = null;
        final ResponseResult result = new ResponseResult();
        try {
            entity = new StringEntity(requestJson, ContentType.APPLICATION_JSON);
            // 封装请求体
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单
                httpPost.setEntity(new UrlEncodedFormEntity(paramList, "utf-8"));
            }

            httpPost.setEntity(entity);
            CloseableHttpResponse httpResponse = null;
            httpResponse = httpClient.execute(httpPost);
            final HttpEntity responseEntity = httpResponse.getEntity();
            httpStr = EntityUtils.toString(responseEntity, "UTF-8");
        } catch (IOException e) {
            System.out.println("HttpClient requestPost Execute Error:" + e);
            httpPost.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException f) {
                System.out.println("HttpClient requestPost Close httpClient Error:" + f);
            }
        } finally {
            httpPost.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException e2) {
                System.out.println("HttpClient requestPost Close httpClient Error:" + e2);
            }
        }
        return httpStr;
    }

    public static String requestTokenPost(final String url) {
        final CloseableHttpClient httpClient = org.apache.http.impl.client.HttpClients.createDefault();
        final HttpPost httpPost = new HttpPost(url);
        String httpStr = "";
        try {
            CloseableHttpResponse httpResponse = null;
            httpResponse = httpClient.execute(httpPost);
            final HttpEntity responseEntity = httpResponse.getEntity();
            httpStr = EntityUtils.toString(responseEntity, "UTF-8");
        } catch (IOException e) {
            System.out.println("HttpClient requestPost Execute Error:" + e);
            httpPost.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException f) {
                System.out.println("HttpClient requestPost Close httpClient Error:" + f);
            }
        } finally {
            httpPost.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException e2) {
                System.out.println("HttpClient requestPost Close httpClient Error:" + e2);
            }
        }
        return httpStr;
    }

    public static String requestPost(final String url, Map<String, String> map) {

        final CloseableHttpClient httpClient = org.apache.http.impl.client.HttpClients.createDefault();
        final HttpPost httpPost = new HttpPost(url);
        HttpEntity multipart = null;
        String httpStr = "";
        ContentType contentType = null;
        final SaveDataResult result = new SaveDataResult();
        try {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
            for (Map.Entry<String, String> stringStringEntry : map.entrySet()) {
                StringBody body = new StringBody(stringStringEntry.getValue(), contentType);
                builder.addPart(stringStringEntry.getKey(), body);
            }
            multipart = builder.build();
            httpPost.setEntity(multipart);
            CloseableHttpResponse httpResponse = null;
            httpResponse = httpClient.execute(httpPost);
            final HttpEntity responseEntity = httpResponse.getEntity();
            httpStr = EntityUtils.toString(responseEntity, "UTF-8");
        } catch (IOException e) {
            System.out.println("HttpClient requestPost Execute Error:" + e);
            httpPost.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException f) {
                System.out.println("HttpClient requestPost Close httpClient Error:" + f);
            }
        } finally {
            httpPost.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException e2) {
                System.out.println("HttpClient requestPost Close httpClient Error:" + e2);
            }
        }
        return httpStr;
    }

    static {
        (HttpClients.connMgr = new PoolingHttpClientConnectionManager()).setMaxTotal(100);
        HttpClients.connMgr.setDefaultMaxPerRoute(HttpClients.connMgr.getMaxTotal());
        final RequestConfig.Builder configBuilder = RequestConfig.custom();
        configBuilder.setConnectTimeout(30000);
        configBuilder.setSocketTimeout(30000);
        configBuilder.setConnectionRequestTimeout(30000);
        HttpClients.requestConfig = configBuilder.build();
    }
}
